package com.scs.application.modules.wm.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.mvc.controller.FlowController;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.util.CommonService;
import com.scs.application.modules.dept.entity.Apply;
import com.scs.application.modules.dept.mapper.ApplyMapper;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.dto.PickDTO;
import com.scs.application.modules.wm.entity.*;
import com.scs.application.modules.wm.enums.UniqueCodeType;
import com.scs.application.modules.wm.mapper.DistItemMapper;
import com.scs.application.modules.wm.service.DistService;
import com.scs.application.modules.wm.service.PickItemService;
import com.scs.application.modules.wm.service.StockService;
import com.scs.application.modules.wm.utils.UniqueCodeUtils;
import com.scs.application.modules.wm.vo.DistVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/wm/dist")
public class DistController extends FlowController<DistService, Dist> {

    @Autowired
    PickItemService pickItemService;
    @Autowired
    ApplyMapper applyMapper;
    @Autowired
    DistItemMapper distItemMapper;
    @Autowired
    StockService stockService;

    /**
     * 拣货，如果原有拣货明细已存在，则取消拣货
     *
     * @return
     */
    @PostMapping("/pick")
    synchronized public RestResult pick(@RequestBody @Valid PickDTO pickDTO) {

        //自动解锁
        String utype = "sn";
        //判断是否为SN，防止扫描到绑定的定数包的sn,如果扫描到的是定数包上的sn，则用RFID查询所有的拣货明细
        if (UniqueCodeUtils.getUniqueCodeType(pickDTO.getUniqueCode()) == UniqueCodeType.SN) {
            Stock stock = stockService.getStockByUniqueCode(pickDTO.getUniqueCode());
            CommonService.checkStock(stock,null);
            if (StringUtils.isNotBlank((stock.getRfid()))){
                utype = "rfid";
                List<Stock> stocklist = stockService.getStockListByUniqueCode(stock.getRfid());
                List<PickItem> pickItemList = pickItemService.list(Wrappers.<PickItem>query().eq(utype, stock.getRfid()).eq("dist_id", pickDTO.getDistId()));
                if (pickItemList.size() != 0) {
                    List<String> idList = new ArrayList<>();
                    for (PickItem pickItem : pickItemList) {
                        idList.add(pickItem.getId());
                    }
                    service.unpick(idList);
                    return RestResult.ok("取消拣货成功");
                }
                for (Stock stock1 : stocklist) {
                    CommonService.checkStock(stock1,null);
                    service.pick(pickDTO.getDistId(), stock1.getSn());
                }


                return RestResult.ok("拣货成功");
            }

        }

        if (UniqueCodeUtils.getUniqueCodeType(pickDTO.getUniqueCode()) == UniqueCodeType.RFID) {
            utype = "rfid";
            List<Stock> stocklist = stockService.getStockListByUniqueCode(pickDTO.getUniqueCode());
            List<PickItem> pickItemList = pickItemService.list(Wrappers.<PickItem>query().eq(utype, pickDTO.getUniqueCode()).eq("dist_id", pickDTO.getDistId()));
            if (pickItemList.size() != 0) {
                List<String> idList = new ArrayList<>();
                for (PickItem pickItem : pickItemList) {
                    idList.add(pickItem.getId());
                }
                service.unpick(idList);
                return RestResult.ok("取消拣货成功");
            }
            for (Stock stock1 : stocklist) {
                CommonService.checkStock(stock1,null);
                service.pick(pickDTO.getDistId(), stock1.getSn());
            }


            return RestResult.ok("拣货成功");
        }


        PickItem pickItem = pickItemService.getOne(Wrappers.<PickItem>query().eq(utype, pickDTO.getUniqueCode()).eq("dist_id", pickDTO.getDistId()));
        if (pickItem != null) {
            service.unpick(Arrays.asList(pickItem.getId()));
            return RestResult.ok("取消拣货成功");
        }
        service.pick(pickDTO.getDistId(), pickDTO.getUniqueCode());

        return RestResult.ok("拣货成功");
    }
    /**
     * 拣货,给移动端用的，需返回结果刷新界面
     *
     * @return
     */
//    @PostMapping("/mobilePick")
//    public RestResult mobilePick(@RequestBody @Valid PickDTO pickDTO) {
//        return RestResult.ok("拣货成功", service.mobilePick(pickDTO.getDistId(), pickDTO.getUniqueCode()));
//    }

    /**
     * 拣货删除
     */
    @DeleteMapping("/unpick")
    public RestResult unpick(@RequestBody Map<String, Object> para) {
        List<String> ids = (List<String>) para.get("ids");
        service.unpick(ids);
        return RestResult.ok("数据删除成功");
    }

    /**
     * 根据配送单号，返回配送单及明细、拣货信息
     *
     * @return
     */
    @RequestMapping("/getDistByKey")
    public RestResult getDistByKey(@RequestParam String distKey) {
        return RestResult.ok("查询成功！", service.getDistByKey(distKey));
    }

    /**
     * 返回配送调度板显示的信息
     *
     * @return
     */
    @RequestMapping("/getDistSchedule")
    public RestResult getDistSchedule() {
        return RestResult.ok("查询成功！", service.getDistSchedule());
    }

    /**
     * 更新拣货人
     *
     * @return
     */
    @PostMapping("/updatePicker")
    public RestResult updatePicker(@RequestBody Map<String, Object> para) {
        service.update(Wrappers.<Dist>update()
                .set("picker", para.get("picker"))
                .eq("id", para.get("id")));
        return RestResult.ok("修改成功！");
    }

    /**
     * 更新收货人和签名
     *
     * @return
     */
    @PostMapping("/updateReceiver")
    public RestResult updateReceiver(@RequestBody Map<String, Object> para) {
        service.updateReceiver(para);
        return RestResult.ok("修改成功！");
    }

    /**
     * 根据订单自动转换配送单
     *
     * @param workOrder
     */
    @PostMapping("/autoChangeDist")
    public RestResult autoChangeDist(@RequestBody WorkOrder workOrder) {
        Dist dist = service.autoChangeDist(workOrder);
        return RestResult.ok("转换成功", dist);
    }

    @GetMapping("/pdfPreview")
    public void pdfPreview(@RequestParam(name = "id") String id,
                           HttpServletResponse response) {
        service.pdfPreview(id, response);
    }

    /**
     * 查询本周运营配送单数量
     *
     * @param
     * @return
     */
    @GetMapping("/findThisWeekDistCount")
    public RestResult findThisWeekDistCount() {
        Integer count = service.findThisWeekDistCount();
        return RestResult.ok("查询成功", count);
    }

    /**
     * 查询本周收货数量
     */
    @GetMapping("/findThisWeekDeliveryCount")
    public RestResult findThisWeekDeliveryCount() {
        Integer count = service.findThisWeekDeliveryCount();
        return RestResult.ok("查询成功", count);
    }

    /**
     * 查询所有非审核通过的调拨单
     *
     * @param
     */
    @GetMapping("/listForPDA")
    public RestResult listForPDA(@RequestParam("busKey") String busKey) {
        List<Map> allList = service.listForPDA(busKey);
        return RestResult.ok("查询成功", allList);
    }

    /**
     * @Description：批量拣货
     */
    @PostMapping("/pickBatch")
    public RestResult pickBatch(@RequestBody @Valid List<PickDTO> pickDTOs) {
        service.pickBatch(pickDTOs);
        return RestResult.ok();
    }

    /**
     * 根据id查询数据
     *
     * @param
     */
    @GetMapping("/findByIdForPDA")
    public RestResult findByIdForPDA(@RequestParam(name = "id") String id) {
        DistVO distVO = service.findByIdForPDA(id);
        return RestResult.ok("查询成功", distVO);
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/findBy")
    @Override
    public RestResult findBy(@RequestParam("key") String key, @RequestParam("value") String value) {
        DistVO entity = service.findBy(key, value);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        return RestResult.ok("获取数据成功", entity);
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        Dist entity = service.getById(id);
        List<DistItem> distItemList = distItemMapper.selectList(Wrappers.<DistItem>query().eq("dist_id",id));
        if (distItemList != null && distItemList.size() > 0) {
            List<String> applyIdList = distItemList.stream().filter(ob -> StringUtils.isNotBlank(ob.getApplyId())).map(DistItem::getApplyId).collect(Collectors.toList());
            if (applyIdList != null && applyIdList.size() > 0) {
                List<Apply> applyList = applyMapper.selectList(Wrappers.<Apply>query().in("id",applyIdList));
                if (applyList != null && applyList.size() > 0) {
                    List<String> remarkList = applyList.stream().filter(ob -> StringUtils.isNotBlank(ob.getRemark())).map(Apply::getRemark).collect(Collectors.toList());
                    if (remarkList != null && remarkList.size() > 0) {
                        entity.setDeptAddressName(StringUtils.join(remarkList,","));
                    }
                }
            }
        }

        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        return RestResult.ok("获取数据成功", entity);
    }
}
